﻿using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace Poi.NET.util
{

    public readonly class IOUtils
    {
        private IOUtils()
        {
            // no instances of this class
        }

        /**
         * Reads all the data from the input stream, and returns the bytes read.
         */
        public static byte[] toByteArray(Stream stream)
        {
            MemoryStream baos = new MemoryStream();

            byte[] buffer = new byte[4096];
            int read = 0;
            while (read != -1)
            {
                read = stream.Read(buffer, 0, buffer.Length);
                if (read > 0)
                {
                    baos.Write(buffer, 0, read);
                }
            }

            return baos.ToArray();
        }

        /**
         * Helper method, just calls <tt>readFully(in, b, 0, b.length)</tt>
         */
        public static int readFully(Stream ins, byte[] b)
        {
            return readFully(ins, b, 0, b.Length);
        }

        /**
         * Same as the normal <tt>in.read(b, off, len)</tt>, but tries to ensure
         * that the entire len number of bytes is read.
         * <p>
         * If the end of file is reached before any bytes are read, returns -1. If
         * the end of the file is reached after some bytes are read, returns the
         * number of bytes read. If the end of the file isn't reached before len
         * bytes have been read, will return len bytes.
         */
        public static int readFully(Stream ins, byte[] b, int off, int len)
        {
            int total = 0;
            while (true)
            {
                int got = ins.Read(b, off + total, len - total);
                if (got < 0)
                {
                    return (total == 0) ? -1 : total;
                }
                total += got;
                if (total == len)
                {
                    return total;
                }
            }
        }

        /**
         * Copies all the data from the given InputStream to the OutputStream. It
         * leaves both streams open, so you will still need to close them once done.
         */
        public static void copy(Stream inp, Stream outs)
        {
            byte[] buff = new byte[4096];
            int count;
            while ((count = inp.Read(buff, 0, buff.Length)) != -1)
            {
                if (count > 0)
                {
                    outs.Write(buff, 0, count);
                }
            }
        }
    }
}
